package org.ws.lifebacklog.util;

import java.io.BufferedReader;
import java.io.Closeable;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;

public class FileUtils {
	private static final int BUFFER_SIZE = 8384;

	/**
	 * Closes the specified stream.
	 * 
	 * @param stream The stream to close.
	 */
	public static void closeStream(Closeable stream) {
		if (stream != null) {
			try {
				stream.close();
			} catch (IOException e) {
			}
		}
	}

	public static void copyStream(InputStream is, OutputStream os) throws IOException {

		try {
			byte[] buff = new byte[BUFFER_SIZE];
			int size;
			while ((size = is.read(buff, 0, buff.length)) != -1) {
				os.write(buff, 0, size);
			}
			os.flush();
		} catch (IOException ex) {
			throw new IOException("Cannot copy stream ");
		} finally {
			closeStream(is);
			closeStream(os);
		}

	}

	public static String readAsString(InputStream is) {
		BufferedReader in = null;
		try {
			in = new BufferedReader(new InputStreamReader(is));
			String line;
			StringBuilder buffer = new StringBuilder();
			while ((line = in.readLine()) != null) {
				buffer.append(line).append('\n');
			}
			return buffer.toString();
		} catch (IOException e) {
			return "";
		} finally {
			closeStream(in);
		}

	}

	public static void appendToFile(String filePath, String content) {
		FileOutputStream fos = null;
		try {
			File file = new File(filePath);
			if (!file.exists()) {
				file.getParentFile().mkdirs();
				file.createNewFile();
			}
			fos = new FileOutputStream(filePath, true);
			fos.write(content.getBytes("UTF-8"));
		} catch (Exception e) {
			Logger.w(FileUtils.class, "can't write log.");
		} finally {
			closeStream(fos);
		}
	}

}
